package org.kl.bf.utils;

import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * @Author hqm
 * @CreateTime 2014年6月20日 上午10:02:13
 * @ChangeLog 2014-07-01 Qken 添加 ISNULL、NOTNULL
 *            表达式，由于KLSearchFilter会过滤空值，故使用时请赋个非空值。
 *            2014-09-28 Qken 添加GTF、LTF表达式
 *            用于两个字段值比较大小 
 *            2014-10-20 Qken 添加EQF、NEQF表达式 
 *            用于两个字段值是否相等
 */
public class KLSearchFilter {
	/**
	 * <pre>
	 * java数据库操作对应前端所选操作
	 * EQ:equal
	 * NEQ:notequal
	 * LIKE:contains
	 * NLIKE:notcontains
	 * GT:greater
	 * LT:less
	 * GTE:greaterorequal
	 * GTF:Greater Than between Fields
	 * LTF Less Than between Fields
	 * 
	 * <pre>
	 * @Author hqm
	 * @CreateTime 2014年8月5日 下午7:56:24
	 */
	public enum Operator {
		EQ, EQF, NEQ, NEQF, LIKE, NLIKE, GT, LT, GTE, LTE, IN, NIN, ISNULL, NOTNULL, GTF, LTF
	}

	public String fieldName;
	public Object value;
	public Operator operator;
	public String javaType;

	public KLSearchFilter(String fieldName, Operator operator, Object value, String javaType) {
		this.fieldName = fieldName;
		this.value = value;
		this.operator = operator;
		this.javaType = javaType;
	}

	/**
	 * searchParams中key的格式为OPERATOR_FIELDNAME或者OPERATOR-JavaType_FIELDNAME
	 */
	public static Map<String, KLSearchFilter> parse(Map<String, Object> searchParams) {
		Map<String, KLSearchFilter> filters = Maps.newHashMap();

		for (Entry<String, Object> entry : searchParams.entrySet()) {
			// 过滤掉空值
			String key = entry.getKey();
			Object value = entry.getValue();
			// 拆分operator与filedAttribute
			String[] names = StringUtils.split(key, "_");
			if (names.length != 2) {
				throw new IllegalArgumentException(key + " is not a valid search filter name");
			}
			String filedName = names[1];
			String[] opers = StringUtils.split(names[0], "-");
			String operatorStr = names[0];

			if (opers.length == 2) {
				operatorStr = opers[0];
			}

			Operator operator = Operator.valueOf(operatorStr);
			if (StringUtils.isBlank((String) value) && !Lists.newArrayList(Operator.NOTNULL, Operator.ISNULL).contains(operator)) {
				continue;
			}
			String javaType = "S";
			if (opers.length == 2) {
				javaType = opers[1];
				if (!Lists.newArrayList("IN", "NIN").contains(opers[0])) {
					value = KLConvertUtils.convertStringToObject((String) value, opers[1]);
				}
			}
			// 创建searchFilter
			KLSearchFilter filter = new KLSearchFilter(filedName, operator, value, javaType);
			filters.put(key, filter);
		}

		return filters;
	}
}
